mod game_core;
mod store;

pub use game_core::GameStartMsg;

use std::thread;
use the_world_game_core::{
    run, Worker,
    result::{Result, anyhow},
};

use futures_channel::mpsc::{unbounded, UnboundedSender};
use std::cell::RefCell;
use futures_util::StreamExt;
use crate::game::game_core::Game;

thread_local! {
    /// 记号通道 用来发送相关信号。目前仅实现的信号：游戏关闭信号
    static SIGN_CHANNEL:RefCell<Option<UnboundedSender<usize>>>={
        RefCell::new(None)
    }
}

pub fn start_game() -> Result<()> {
    SIGN_CHANNEL.with(|sender: &RefCell<Option<UnboundedSender<usize>>>| -> Result<()> {
        if sender.borrow().is_some() {
            // 重复启动错误
            return Err(anyhow!("同一时间启动多个游戏"));
        }
        // 创建通道，用来进行新号传递，进行游戏的关闭
        let (s, mut r) = unbounded::<usize>();
        *sender.borrow_mut() = Some(s);
        thread::spawn(|| {
            run(async move {
                let game = Game::new();
                game.run(None);
                while let Some(sign) = r.next().await {
                    match sign {
                        0 => {
                            println!("正常关闭");
                            break;
                        }
                        _ => {
                            println!("错误信号{}", sign);
                        }
                    }
                }
            })
        });
        Ok(())
    })
}

pub fn stop_game() -> Result<()> {
    SIGN_CHANNEL.with(|channel_ref| -> Result<()> {
        if channel_ref.borrow().is_none() {
            // 没有游戏可以关闭
            return Err(anyhow!("关闭不存在的游戏"));
        }
        let channel_borrow=channel_ref.borrow();
        let channel = channel_borrow.as_ref().unwrap();
        channel.unbounded_send(0);
        *channel_ref.borrow_mut() = None;
        Ok(())
    })
}
